#
# 【下载器】
#
# requests 模块需要安装
# sudo pip3 install requests
#
# 对外提供一个方法：
#
# download(url)
# 下载网页中的内容，接收一个参数 URL
#
from abc import abstractmethod
from typing import Union

import requests
from requests.cookies import RequestsCookieJar

from sam.util.httpUtil import http_get


class Download(object):
    def __init__(self):
        super().__init__()

    @abstractmethod
    def prepare_cookies(self) -> Union[dict, RequestsCookieJar]:
        pass

    @abstractmethod
    def prepare_proxies(self) -> dict:
        pass

    @staticmethod
    def _prepare_cookies_demo() -> Union[dict, RequestsCookieJar]:
        cookies = []
        cookie_jar = requests.cookies.RequestsCookieJar()
        for cookie in cookies:
            cookie_jar.set(
                name=cookie["name"]
                , value=cookie["value"]
                , domain=cookie["domain"]
                , path=cookie["path"]
            )
        return cookie_jar

    def download(self, url):
        # 判断 URL 是否为空，为空直接返回 None
        # if url is None:
        #     return None
        if url:
            # 请求 URL
            response = http_get(url=url, cookies=self.prepare_cookies(), proxies=self.prepare_proxies())
            # 判断 URL 地址是否访问成功，若失败直接返回 None
            if response.status_code == requests.codes.ok:
                return response.text
